import asyncio
from random import random

async def task_processor(task_id):
    """模拟任务处理过程的异步生成器"""
    try:
        # 数据准备阶段
        await asyncio.sleep(0.5)
        yield f"任务 {task_id}: 数据准备中"
        
        # 处理阶段
        progress = 0
        while progress < 100:
            await asyncio.sleep(0.1)
            if random() < 0.1:  # 10%概率模拟失败
                raise Exception("模拟随机错误")
            progress += 10 + int(random() * 20)
            progress = min(progress, 100)
            yield f"任务 {task_id}: 处理中 ({progress}%)"
        
        # 成功完成
        yield f"任务 {task_id}: 处理完毕"
        
    except Exception as e:
        # 处理失败
        yield f"任务 {task_id}: 处理失败 - {str(e)}"

async def monitor_tasks():
    """监控多个任务的处理状态"""
    tasks = [task_processor(i) for i in range(3)]
    
    # 使用async for跟踪每个任务的状态
    for task in tasks:
        async for status in task:
            print(status)
            if "失败" in status or "完毕" in status:
                break  # 任务结束

if __name__ == "__main__":
    asyncio.run(monitor_tasks())